﻿using log4net;
using System;
using System.IO;
using System.Linq;
using System.Text;
using VisioERLeveller.Visio;

namespace VisioERLeveller {

    internal class Program {

        private static readonly ILog LOG = LogManager.GetLogger(typeof(Program));

        static void Main(string[] args) {
            var filepath = args.Length > 0 ? args[0] : throw new ArgumentNullException("FileName");
            var pageName = args.Length > 1 ? args[1] : throw new ArgumentNullException("PageName");
            var outputPath = args.Length > 2 ? args[2] : throw new ArgumentNullException("Output");

            filepath = Path.GetFullPath(filepath);
            outputPath = Path.GetFullPath(outputPath);

            try {
                Leveller leveller = new();

                using var reader = Visio2013ERDialet.CreateReader(filepath, pageName);
                var graph = reader.ReadGraph();
                LevellizeResult result = leveller.Levellize(graph);

                Encoding utf8 = new UTF8Encoding(false);
                using var writer = new StreamWriter(outputPath, false, utf8);

                writer.WriteLine($"Basic Information:");
                writer.WriteLine($"\tFile: {filepath}");
                writer.WriteLine($"\tPage: {pageName}");
                writer.WriteLine($"\tMax Depth: {result.MaxDepth}");
                writer.WriteLine($"\tRings: {result.Rings}");
                writer.WriteLine($"\tMax Ring Length: {result.MaxRingLength}");
                writer.WriteLine();

                var list = from kvp in result.NodeLevels
                           let node = graph.GetNode(kvp.Key)
                           let item = new {
                               node.Name,
                               Depth = kvp.Value,
                               Text = node.Text,
                           }
                           orderby item.Depth, item.Text
                           select item;

                writer.WriteLine($"Nodes with depth:");
                foreach (var item in list) {
                    writer.WriteLine($"\t{item.Depth} ({item.Name}): {item.Text}");
                }
            } catch (Exception err) {
                LOG.Fatal($"Fatal error", err);
            }
        }
    }
}
